package com.stalltea.easypool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yilvchangfa
 * @since 2021/11/30 16:59
 **/
public class ConnectionPoolTest {

    /**
     * 线程开始一起获取链接的开关
     */
    static CountDownLatch start = new CountDownLatch(1);

    /**
     * 要等待完成的线程数
     */
    static CountDownLatch end;

    public static void main(String[] args) throws Exception {
        // 线程数量
        int threadCount = 30;
        end = new CountDownLatch(threadCount);
        // 每个线程的执行次数
        int count = 20;

        // 获取到连接的次数
        AtomicInteger got = new AtomicInteger();
        // 没获取到连接的次数
        AtomicInteger notGot = new AtomicInteger();

        ConnectionPool pool = new ConnectionPool(10);
        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(new ConnectionRunner(got, notGot, count, pool));
            thread.start();
        }
        start.countDown();
        end.await();
        System.out.println("count:" + count * threadCount);
        System.out.println("got:" + got.get());
        System.out.println("notGot:" + notGot.get());

    }

    static class ConnectionRunner implements Runnable {

        // 获取到连接的次数
        AtomicInteger got;

        // 没获取到连接的次数
        AtomicInteger notGot;

        int count;

        ConnectionPool pool;

        public ConnectionRunner(AtomicInteger got, AtomicInteger notGot, int count, ConnectionPool pool) {
            this.got = got;
            this.notGot = notGot;
            this.count = count;
            this.pool = pool;
        }

        @Override
        public void run() {
            try {
                start.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (count > 0) {
                try {
                    Connection connection = pool.fetchConnection(1000);
                    if (null == connection) {
                        notGot.incrementAndGet();
                    } else {
                        try {
                            connection.commit();
                        } finally {
                            pool.releaseConnection(connection);
                            got.incrementAndGet();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }

}
